package fifthquestion;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

public class MsgSender {
        public static void main(String[] args) {
            //声明数据报socket
            DatagramSocket ds = null;
            //声明数据报文
            DatagramPacket dp = null;
            //v创建文本扫描机器
            Scanner scanner = new Scanner(System.in);
            //声明临时存放数据的缓存区
            byte[] bytebuffer = null;
            //创建inetaddress对象
            String host = "127.0.0.1";
            int port=8800;

            byte[] buf = new byte[1025];
            try {
                ds = new DatagramSocket();
                String line = null;
                String massage=null;
                InetAddress serverAddr=InetAddress.getByName(host);
                while (true){
                    //faos发送数据报给接受者
                    System.out.println("请输入信息");
                    line=scanner.next();
                    if ("over".equalsIgnoreCase(line)){
                        break;
                    }
                    bytebuffer=line.getBytes(Charset.forName("utf-8"));
                    //创建数据报封装发送给服务器
                    dp=new DatagramPacket(bytebuffer,bytebuffer.length,serverAddr,port);
                    ds.send(dp);

                    //接收服务器的响应
                    dp = new DatagramPacket(buf,buf.length);
                    ds.receive(dp);
                    //分析数据报
                    massage = new String(dp.getData(),0,dp.getLength());
                    System.out.println();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


